<template>
    <div>
        <canvas ref="canvas1"></canvas>
        <canvas ref="canvas2"></canvas>
        <button @click="compare">判断是否为同一个人</button>
    </div>
</template>
  
<script>
import cv from 'opencv.js'

export default {
    data() {
        return {
            signature1: null, // 第一次手写签名的图像对象
            signature2: null, // 第二次手写签名的图像对象
        }
    },
    mounted() {
        cv.onRuntimeInitialized = () => {
            // OpenCV.js已经加载完成，可以开始使用
            // 在组件挂载完成后，将图片转化为图像对象
            this.getImage(this.$refs.canvas1, 'signature1.png', (image) => {
                this.signature1 = image
            })
            this.getImage(this.$refs.canvas2, 'signature2.png', (image) => {
                this.signature2 = image
            })
        }
    },
    methods: {
        getImage(canvas, imgSrc, callback) {
            const ctx = canvas.getContext('2d')
            const img = new Image()
            img.src = imgSrc
            img.onload = () => {
                canvas.width = img.width
                canvas.height = img.height
                ctx.drawImage(img, 0, 0)
                const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
                const image = cv.matFromImageData(imageData)
                callback && callback(image)
            }
        },
        compare() {
            if (!this.signature1 || !this.signature2) {
                return alert('请先上传图片')
            }

            const result = new cv.Mat()
            const method = cv.TM_CCOEFF_NORMED
            cv.matchTemplate(this.signature1, this.signature2, result, method)

            const maxVal = cv.minMaxLoc(result).maxVal
            if (maxVal > 0.8) {
                alert('是同一个人')
            } else {
                alert('不是同一个人')
            }

            result.delete()
            this.signature1.delete()
            this.signature2.delete()
        },
    },
}
